package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 31803
* @description 针对表【tb_dict】的数据库操作Service实现
* @createDate 2025-06-24 10:28:35
*/
@Service
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
    implements TbDictService{
    @Autowired
    TbDictMapper tbDictMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @PostConstruct
    public void loadDictList(){
        System.out.println("项目启动时，加载字典表到缓存中");
        List<TbDict> tbDictList = tbDictMapper.selectList(null);
        for (TbDict tbDict : tbDictList) {
            String key1="dict-"+tbDict.getDictType();
            String key2=tbDict.getDictId().toString();
            redisTemplate.opsForHash().put(key1,key2, JSON.toJSONString(tbDict));
        }
        System.out.println("加载数据完成");
    }


    @Override
    public R getDictList(Integer typeId) {
        //首先检查缓存中是否存在数据
        String key1="dict-"+typeId;
        Boolean hasKey = redisTemplate.hasKey(key1);
        if(hasKey){
            System.out.println("从缓存中获取");
            List<Object> objectList = redisTemplate.opsForHash().values(key1);
            ArrayList<TbDict> tbDicts = new ArrayList<>();
            for (Object o : objectList) {
                TbDict tbDict = JSON.parseObject(o.toString(), TbDict.class);
                tbDicts.add(tbDict);
            }
            return R.ok().setData(tbDicts);
        }else{
            //2缓存中不存在从数据库中读取
            System.out.println("从数据库中获取数据");
            List<TbDict> tbDictList = tbDictMapper.selectList(new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, typeId));
            for (TbDict tbDict : tbDictList) {
                String key2="dict-"+tbDict.getDictType();
                String key3=tbDict.getDictId().toString();
                String key4=JSON.toJSONString(tbDict);
                redisTemplate.opsForHash().put(key2,key3,key4);
            }
            return R.ok().setData(tbDictList);
        }
    }
}




